<template>
  <section>
    <div style="text-align:center; backgroundColor: #fff;">
      <!-- tabs工具条 -->
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane label="资产申请" name="first">
          <el-form
            :model="seachForm"
            ref="numberValidateForm"
            label-width="150px"
            class="demo-ruleForm"
          >
            <el-row>
              <el-col :span="6">
              <el-form-item label="商户ID:" prop="merchantId">
                  <el-input v-model="seachForm.merchantId" disabled></el-input>
              </el-form-item>
              </el-col>
              <el-col :span="6">
              <el-form-item label="状态:" prop="status">
                <el-select
                  placeholder="待审核"
                  clearable
                  v-model="seachForm.status"
                  class="project"
                >
                  <el-option
                    v-for="item in region"
                    :label="item.name"
                    :key="item.code"
                    :value="item.code"
                  ></el-option>
                </el-select>
              </el-form-item>
              </el-col>
             <el-col :span="15">
              <el-form-item label="时间段:" >
                <el-date-picker
                  v-model="seachForm.startTime"
                  type="datetime"
                  :editable="false"
                  placeholder="选择开始日期"
                  value-format = "yyyy-MM-dd HH:mm:ss"
                  :picker-options="pickerOptions"
                  @change="end"
                ></el-date-picker>~
                <el-date-picker
                  v-model="seachForm.endTime"
                  type="datetime"
                  :editable="false"
                  placeholder="选择结束日期"
                  value-format = "yyyy-MM-dd HH:mm:ss"
                  :picker-options="pickerOptions"
                  @change="start"
                ></el-date-picker>
                <el-button type="primary" class="checkBtn" @click="search()">查询</el-button>      
              </el-form-item>
              </el-col>
            </el-row>
          </el-form>

          <template>
            <el-table :data="tableData" border style="width: 100%">
              <el-table-column type="index" align="center"></el-table-column>
              <el-table-column prop="merchantId" label="商户ID" align="center" width="150"></el-table-column>
              <el-table-column prop="merchantType" label="商户类型" align="center" width="120"></el-table-column>
              <el-table-column prop="businessType" label="业务类型" align="center" width="120">
                  <template slot-scope="scope">
                      {{getbusType(scope.row.businessType)}}
                  </template> 
              </el-table-column>              
              <el-table-column prop="sourceMerchantId" label="源商户ID" align="center" width="120"></el-table-column>
              <el-table-column prop="targetMerchantId" label="目的商户ID" align="center" width="120"></el-table-column>
              <el-table-column prop="handleUser" label="操作者" align="center" width="120"></el-table-column>
              <el-table-column prop="createTime" label="创建时间" align="center" width="190"></el-table-column>
              <el-table-column prop="currency" label="币种" align="center" width="120"></el-table-column>              
              <el-table-column prop="money" label="调整额度" align="center" width="120"></el-table-column>              
              <el-table-column prop="collectionMethod" label="收款方式" align="center" width="120"></el-table-column>
              <el-table-column prop="status" label="状态" align="center" width="120">
                  <template slot-scope="scope">
                      {{getapplyStatus(scope.row.status)}}
                  </template> 
              </el-table-column>
            </el-table>
            <div class="block">
                <el-pagination
                  background
                  @size-change="pageSizeChange"
                  @current-change="pageIndexChange"
                  :current-page="pageIndex"
                  :page-size="pageSize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="dataTotal"
                ></el-pagination>
            </div>
          </template>
        </el-tab-pane>
        <el-tab-pane label="添加" name="second">
          <div style="padding:0 20%;margin: 20px auto;">
            <el-form :label-position="labelPosition" label-width="150px" :model="numberValidateForm" :rules="registrules" ref="numberValidateForm">
              <el-form-item label="商户ID:" prop="merchantId" style="display:none;">
                <el-input v-model="numberValidateForm.merchantId" disabled></el-input>
              </el-form-item>
              <el-form-item label="识别码:" prop="nonce">
                <el-input v-model="numberValidateForm.nonce" disabled></el-input>
              </el-form-item>
              <el-form-item label="商户公钥:" prop="apiKey">
                <el-input v-model="numberValidateForm.apiKey" disabled></el-input>
              </el-form-item>
              <el-form-item label="商户公钥:" prop="apiKeyHide" style="display:none;">
                <el-input v-model="numberValidateForm.apiKeyHide" ></el-input>
              </el-form-item>
              <el-form-item label="调整金额:" prop="money">
                <el-input v-model.number="numberValidateForm.money"></el-input>
              </el-form-item>
              <el-form-item label="收款方式:" prop="collectionMethod">
                  <el-input v-model="numberValidateForm.collectionMethod"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitForm('numberValidateForm')" :loading="addLoad">确定</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <transition name="el-fade-in-linear">
          <div class="spin-container" v-if="gridLoading">
            <div class="spin1">
              <div class="spin2">
              </div>
                <div class="spin3">
              </div>
            </div>
          </div>
    </transition>
  </section>
</template>
<script>
import enums from '../../common/Enum';
import DataUtil from "../../common/dataUtil";
import { getMerchantAssetApplyList,addMerchantAssetApply  ,getSecretById } from "@/api/index.js";

export default {
  inject: ['reload'],
  data() {
    return {
      pickerOptions :{
          disabledDate(time) {
            return time.getTime() > Date.now();
          }
      },
      gridLoading: false,
      addLoad : false,
      resetLoad :false,
      activeName: "first",
      pageIndex: this.$store.getters.getOrderListAllIndex,
      pageSize: 10,
      dataTotal: 0,
      labelPosition: "right",
      seachForm: {
        merchantId: JSON.parse(DataUtil.userInfo()).id,
        status: "",
        startTime: DataUtil.formatUnixDateMin(new Date()),
        endTime: DataUtil.formatUnixDateMax(new Date())
      },
      numberValidateForm: {
        merchantId: JSON.parse(DataUtil.userInfo()).id,
        nonce: "",
        apiKey : '',
        apiKeyHide : '',
        money: "",
        collectionMethod: ""
      },
      registrules: {
        merchantId : [{ required: true, message: "请选输入商户ID", trigger: "blur" }],
        nonce : [{ required: true, message: "请输入标识码", trigger: "blur" }],
        apiKey : [{ required: true, message: "请选输入商户公钥", trigger: "blur" }],
        money: [
            {   required: true,
                type: 'number',
                min: 0,
                message: '金额为数字',
                trigger: 'blur'
            }
        ],
        collectionMethod: [{ required: true, message: "请选择收款方式", trigger: "change" }],
      },
      applyStatus : enums.applyStatus,
      region:enums.applyStatus,
      tableData: [],
    };
  },
  methods: {
    pageIndexChange(val) {
				this.pageIndex = val;
				this.$store.dispatch('getCreditListIndex', val)
				this.search();
    },
    pageSizeChange(val) {
    },
    handleClick(e){
      if(e.index == '0'){
         this.bindGrid();
      }else if(e.index == '1'){
         this.getPubKey();
      }
      this.numberValidateForm.nonce = DataUtil.getNum(10,32);
    },
    search() {
      this.bindGrid();
    },
    getbusType(type){
      return enums.getbusType(type);
    },
    getapplyStatus(type){
      return enums.getapplyStatus(type);
    },
    gethandleType(type){
      return enums.getbusType(type);
    },
    end(e){
      this.seachForm.startTime = e;
    },
    start(e){
      this.seachForm.endTime = e;
    },
    ////////////查询
    bindGrid() {
      
      if( this.seachForm.startTime && this.seachForm.endTime){ 
          if(this.seachForm.startTime > this.seachForm.endTime){
              this.$message.error("开始时间不能大于结束时间！");
              return
          }
      }else{
        this.seachForm.startTime = '';
        this.seachForm.endTime = '';
      }
      let tableData = [];
      const formData = new FormData();
          this.gridLoading = true;
          formData.append('pageNum',this.pageIndex);
          formData.append('merchantId',JSON.parse(DataUtil.userInfo()).id);
          formData.append('status',this.seachForm.status);
          formData.append('minTime',this.seachForm.startTime);
          formData.append('maxTime',this.seachForm.endTime);
          getMerchantAssetApplyList(formData).then(response => {
            if ('01001' == response.status) {
              this.gridLoading = false;
                tableData = response.data.dataList;
                this.tableData = tableData;
                // formData.delete("pageNum");
                // formData.delete("merchantId");
                // formData.delete("status");
                // formData.delete("minTime");
                // formData.delete("maxTime");
                this.dataTotal = response.data.page.recordCount;
            } else {
                this.tableData = [];
                // formData.delete("pageNum");
                // formData.delete("merchantId");
                // formData.delete("status");
                // formData.delete("minTime");
                // formData.delete("maxTime");
                this.$message.error(response.msg);
                this.dataTotal = 0;
            }
          }, response => {
            this.gridLoading = false;
          });
    },
    ////////添加商户资产申请
    submitForm(formName ){
        this.addLoad = true;
        this.$refs[formName].validate(valide => {
          if (valide) {
            const formData = new FormData();
                  formData.append('merchantId',this.numberValidateForm.merchantId);
                  formData.append('nonce',this.numberValidateForm.nonce);
                  formData.append('apiKey',this.numberValidateForm.apiKeyHide);
                  formData.append('money',this.numberValidateForm.money);
                  formData.append('collectionMethod',this.numberValidateForm.collectionMethod);
              addMerchantAssetApply(formData).then(response => {
                if ('01001' == response.status) {
                    this.addLoad = false;
                    this.$message({
                        message: '添加成功！',
                        type: 'success'
                    });
                    // formData.delete("merchantId");
                    // formData.delete("nonce");
                    // formData.delete("apiKey");
                    // formData.delete("money");
                    // formData.delete("collectionMethod");
                    this.reload();
                    this.$router.replace({path: '/MerchantApply',query: {}})
                } else {
                    // formData.delete("merchantId");
                    // formData.delete("nonce");
                    // formData.delete("apiKey");
                    // formData.delete("money");
                    // formData.delete("collectionMethod");
                    this.$message.error(response.msg);
                    this.addLoad = false;
                    this.numberValidateForm.nonce = DataUtil.getNum(10,32);
                }
              }, response => {});
          }else{
            this.numberValidateForm.nonce = DataUtil.getNum(10,32);
            this.addLoad = false;
            this.$message.error('输入不正确！');
          }
        });  
    },
    /////获取商户公钥
    getPubKey() {
      const formData = new FormData();
      formData.append('merchantId',JSON.parse(DataUtil.userInfo()).id);
      getSecretById(formData).then(response => {
        if ('01001' == response.status) {
          if(response.data){
            let hidestr;
            let showstr;
            let char = '';
             hidestr = response.data.publicKey;
             this.numberValidateForm.apiKeyHide = hidestr;
             showstr = response.data.publicKey;
              for (let i = 0, len = showstr.substr(4,60).length; i < len; i++) {
                char += '*';
              }
              showstr = showstr.substr(0,4) + char + showstr.substr(60);
              this.numberValidateForm.apiKey = showstr;
              // formData.delete('merchantId');
          }
        }else{
          // formData.delete("merchantId");
        }
      }, response => {});
    },
  },
  mounted: function() {
      this.bindGrid();
  },
};
</script>
<style>
.blur {
  position: absolute;
  left: 50%;
  top: 50%;
  margin-left: -10%;
  margin-top: 0;
}
.el-pagination {
  display: inline-block;
  width: 80%;
}
.block {
  padding: 10px 0;
}
.spin-container {
    background: rgba(0,0,0,.1)!important;
}
</style>
